//
//  LookupSelectView.m
//  MClient
//
//  Created by  史正烨 on 10-9-7.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "LookupSelectView.h"
#import "MCFunction.h"
#import "MCControl.h"
#import "MCUIToolkit.h"
#import "MServerDAO.h"
#import "EditFormController.h"

NSMutableDictionary *listData;
int selectRow;

@interface LookupSelectView(Private)
////    NSMutableDictionary *listData;
//    int selectRow;
- (id)initWithView:(MCControl*)view;
- (void)layoutFrame:(CGRect)frame;
- (void)show;
@end

@implementation LookupSelectView
@synthesize textFieldView;
@synthesize fieldData;
@synthesize isShown;
@synthesize dataObjectName;
@synthesize listLayout;
@synthesize queryFilter;
@synthesize datas;
@synthesize fieldName;	
@synthesize lookupBackFills;
@synthesize parentViewController;

static LookupSelectView *lookupSelectInstance = nil;

+ (LookupSelectView *)instance {
	@synchronized(self) {
		if (lookupSelectInstance == nil) {
			lookupSelectInstance = [[self alloc] initWithView:nil];
		}
	}
	return lookupSelectInstance;
}

- (id)initWithView:(MCControl*)view {
    if (self = [super initWithFrame:CGRectZero]) {
        // Initialization code
		textFieldView = view;
		isShown = NO;
		selectPicker = [[MCSelectPicker alloc] initWithFrame:CGRectZero];
		[self addSubview:selectPicker];
		
		toolBar = [[UIToolbar alloc] initWithFrame:CGRectZero];
		[self addSubview:toolBar];
		toolBar.barStyle = UIBarStyleDefault;
		[toolBar sizeToFit];
		MCUserDefaults *defaults = [MCUserDefaults instance];
		toolBar.tintColor = defaults.skin_navigationBarColor;
		NSString *title = @"选择";
		UIBarButtonItem *cancelBtn = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStyleBordered target:self action:@selector(selectCancelAction)];	
		UIBarButtonItem *flexItem1 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
		titleBtn = [[UIBarButtonItem alloc] initWithTitle:title style:UIBarButtonItemStylePlain target:nil action:nil];
		UIBarButtonItem *flexItem2 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
		UIBarButtonItem *confirmBtn = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStyleBordered target:self action:@selector(selectAction)];
		
		[toolBar setItems:[NSArray arrayWithObjects:cancelBtn, flexItem1, titleBtn, flexItem2, confirmBtn, nil] animated:NO];
		[cancelBtn release];
		[flexItem1 release];
		[flexItem2 release];
		[confirmBtn release];
    }
    return self;
}

#define nLookupSelectToolBarHeight    28
#define nLookupSelectPickerHeight     nPickerHeight

- (void)layoutFrame:(CGRect)frame
{
	self.frame = CGRectMake(0, CGRectGetMaxY(frame), CGRectGetMaxX(frame), nLookupSelectPickerHeight+nLookupSelectToolBarHeight);
	self.autoresizingMask = nMCViewAutoresizingMask;
	selectPicker.frame = CGRectMake(0, nLookupSelectToolBarHeight, CGRectGetMaxX(frame), nLookupSelectPickerHeight);
	selectPicker.autoresizingMask = nMCViewAutoresizingMask;
	toolBar.frame = CGRectMake(0, 0, CGRectGetMaxX(frame), nLookupSelectToolBarHeight);
	toolBar.autoresizingMask = nMCViewAutoresizingMask;
}

- (void)dealloc {
	[fieldData release];
	[dataObjectName release];
	[listLayout release];
	[queryFilter release];
	[datas release];
	[fieldName release];	
	[lookupBackFills release];
	[titleBtn release];
	[selectPicker release];
	[toolBar release];
    [super dealloc];
}

#pragma mark ---- 数据加载方法 ----
- (void)getDataFromServer {
	[[MServerDAO sharedInstance] getListDataAsync:dataObjectName 
									   layoutName:[self.listLayout objectForKey:@"layout"] 
									  queryFilter:queryFilter
											 page:-1
										 delegate:self];
}

- (void)getDataFromServerSuccess: (NSMutableDictionary *)returnValue {
	listData = [returnValue retain];
	parentViewController.navigationController.navigationBar.userInteractionEnabled = NO;
	[selectPicker._picker reloadAllComponents];
	[self show];
}

- (void)return2Parent
{
	parentViewController.navigationController.navigationBar.userInteractionEnabled = YES;
	[self removeFromSuperview];
	isShown = !isShown;
	lookupSelectInstance = nil;
}

- (void)selectCancelAction
{	
	CGRect originFrame = self.frame;
	CGRect finalFrame = CGRectMake(originFrame.origin.x, 
								   CGRectGetMinY(originFrame)+originFrame.size.height, 
								   originFrame.size.width, 
								   originFrame.size.height);
	
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:0.3];
	[UIView setAnimationDelegate:self];
	[UIView setAnimationDidStopSelector:@selector(return2Parent)];
	self.frame = finalFrame;
	[UIView commitAnimations];  
}

- (void)selectAction
{
	[self selectCancelAction];
	
	if (textFieldView) {
		textFieldView.text = selectPicker._label == nil?@"":selectPicker._label;
		[fieldData setObject:selectPicker._value == nil?@"":selectPicker._value forKey:@"value"];
		[fieldData setObject:selectPicker._label == nil?@"":selectPicker._label forKey:@"lbl"];
		selectRow = selectPicker._row;
		textFieldView = nil;
		
		NSMutableDictionary *fieldLabelData = [NSMutableDictionary dictionary];
		[fieldLabelData setObject:selectPicker._label == nil?@"":selectPicker._label forKey:@"value"];
		[datas setObject:fieldLabelData forKey:[@"__" stringByAppendingString:fieldName]];
		
		if (lookupBackFills != nil) {
			for(int k = 0; k<[lookupBackFills count]; k++){
				NSMutableDictionary *lookupBackFill = [lookupBackFills objectAtIndex:k];
				NSString *name = [lookupBackFill objectForKey:@"bf"];
				NSMutableDictionary *recordData = [selectPicker._record objectForKey:@"data"];
				if (recordData == nil) {
					recordData = [NSMutableDictionary dictionary];
				}
				NSMutableDictionary *fieldDataLookupBack = [recordData objectForKey:name];
				if(fieldDataLookupBack == nil)
					fieldDataLookupBack = [NSMutableDictionary dictionary];
				[(EditFormController*)parentViewController setLookupBackFillByFieldName: [lookupBackFill objectForKey:@"fld"] fieldDataLookupBack:fieldDataLookupBack];	
			}
		}
	}
}

- (void)show
{
	if (nil != [fieldData objectForKey:@"value"] && ![@"" isEqualToString:[fieldData objectForKey:@"value"]]) {
		for (int i = 0; i < [[listData objectForKey:@"rl"] count]; i++) {
			NSString *key = [[[listData objectForKey:@"rl"] objectAtIndex:i] objectForKey:@"key"];
			if ([key isEqualToString:[fieldData objectForKey:@"value"]]) {
				selectRow = i;
				break;
			}
		}
		selectPicker._value = [fieldData objectForKey:@"value"];
		selectPicker._label = [fieldData objectForKey:@"lbl"];
		[selectPicker._picker selectRow:selectRow inComponent:0 animated:NO];
	}else {
		if ([[listData objectForKey:@"rl"] count] > 0) {
			selectPicker._value = [[[listData objectForKey:@"rl"] objectAtIndex:0] objectForKey:@"key"];
			selectPicker._label = [[[listData objectForKey:@"rl"] objectAtIndex:0] objectForKey:@"desc"];
		}
		[selectPicker._picker selectRow:0 inComponent:0 animated:NO];
	}

	titleBtn.title = [listLayout objectForKey:@"lbl"];
	
	if (!isShown) {
		[self layoutFrame:parentViewController.clientView.bounds];
		[parentViewController.clientView addSubview:self];
		parentViewController.navigationController.navigationBar.userInteractionEnabled = NO;
		
		CGRect originFrame = self.frame;
		CGRect finalFrame = CGRectMake(originFrame.origin.x, 
									   CGRectGetMinY(originFrame)-originFrame.size.height, 
									   originFrame.size.width, 
									   originFrame.size.height);
		
		[UIView beginAnimations:nil context:NULL];
		[UIView setAnimationDuration:0.3];
		self.frame = finalFrame;
		[UIView commitAnimations];
		isShown = !isShown;
	}
}
@end

@implementation MCSelectPicker
@synthesize _picker;
@synthesize _value;
@synthesize _label;
@synthesize _row;
@synthesize _record;

- (id)initWithFrame:(CGRect)frame
{
	if (self = [super initWithFrame:frame]) {
		_picker = [[UIPickerView alloc] initWithFrame:self.bounds];
		[self addSubview:_picker];
		_picker.delegate = self;
		_picker.dataSource = self;
		_picker.showsSelectionIndicator = YES;
	}
	return self;
}

- (void)dealloc
{
	[_picker release];
	[super dealloc];
}


- (void)layoutSubviews
{
	_picker.frame = self.bounds;
}

// returns the number of 'columns' to display.
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
	return 1;
}

// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
	return [[listData objectForKey:@"rl"] count];	
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
	CGRect rc = CGRectMake(20, 0, 280, 50);
	UILabel *label = [[UILabel alloc] initWithFrame:rc];
	label.backgroundColor = [UIColor clearColor];
	label.text = [[[listData objectForKey:@"rl"] objectAtIndex:row] objectForKey:@"desc"];
	[label setFont:[UIFont boldSystemFontOfSize:18]];
	label.textAlignment = UITextAlignmentCenter;
	return label;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
	_record = [[listData objectForKey:@"rl"] objectAtIndex:row];
	_value = [_record objectForKey:@"key"];
	_label = [_record objectForKey:@"desc"];
	_row = row;
}

@end

